import router from '@/router'
import store from '@/store'
import Nprogress from 'nprogress'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'

/* 白名单页面数组(不需要登录就能访问) */
const whiteList = ['/login', '/404']

/* 全局前置导航守卫 */
router.beforeEach(async(to, from, next) => {
  Nprogress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      next(false)
      Message.warning('已经登录')
    } else {
      const userId = store.getters.userId
      if (userId) {
        next()
      } else {
        try {
          const { roles } = await store.dispatch('userStore/fetchUserInfo')
          // 派发action过滤出最终路由，返回最终路由
          const resultRoutes = await store.dispatch('menuStore/addRoutesAction', roles.menus)
          // 添加最终路由到路由系统(404路由必须在最后)
          router.addRoutes([...resultRoutes, { path: '*', redirect: '/404', hidden: true }])
          next({ ...to, replace: true })
        } catch (error) {
          Message.error('重新登录')
          store.dispatch('userStore/userLogout')
          router.push({ path: '/login', query: { return_url: to.fullPath } })
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Message.warning('请先登录')
      next('/login')
    }
  }
  Nprogress.done()
})

/* 全局后置导航守卫 */
router.afterEach((to, from) => {
  Nprogress.done()
})

